package com.wzd.testimage.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.util.ArrayList;

/**
 * Created by hello on 15-7-3.
 */
public class SVTest extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder sh;
    private MyThread mMyThread;
    boolean isRun=false;
    private ArrayList<Point> list=new ArrayList<>();
    public SVTest(Context context) {
        super(context);
        Log.i("wzd","SV创建");
        sh = this.getHolder();
        sh.addCallback(this);
        mMyThread = new MyThread(sh);
    }

    public SVTest(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isRun=true;
        mMyThread.start();
        Log.i("wzd","创建");
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.i("wzd", format + " " + width + " " + height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isRun=false;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_MOVE:
                Point point = new Point();
                point.x = event.getX();
                point.y = event.getY();
                Log.i("wzd", "x:" + point.x + "y:" + point.y);
                list.add(point);
                break;
        }
        return true;
    }
    class MyThread extends Thread{
        private SurfaceHolder sh;
        MyThread(SurfaceHolder sh){
            this.sh =sh;
        }

        @Override
        public void run() {
            while (isRun) {
                synchronized (sh) {
                    Canvas c = sh.lockCanvas();
                    c.drawColor(Color.WHITE);
                    Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
                    p.setStrokeWidth(10);
                    p.setStyle(Paint.Style.STROKE);
                    p.setColor(Color.BLUE);
                    Path path = new Path();
                    for (Point point : list) {
                        path.lineTo(point.x, point.y);
                        path.moveTo(point.x, point.y);
                    }
                    c.drawPath(path, p);
                    sh.unlockCanvasAndPost(c);
                }
            }
        }
    }
    class Point{
        float x;
        float y;
    }
}
